package com.example.android.commitcontent.ime.keyboard.event_handler;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;

/**
 * 处理退格键长按删除事件
 */
public class BackspaceKyeEventHandler implements View.OnTouchListener {

    private static final int mDelayMillis = 120;
    private BackspaceEventListener mBackspaceEventListener;

    public BackspaceKyeEventHandler(BackspaceEventListener backspaceEventListener) {
        mBackspaceEventListener = backspaceEventListener;
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mBackspaceEventListener.onReceivedBackspaceEvent();
            sendEmptyMessageDelayed(0, mDelayMillis);
        }
    };

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mHandler.sendEmptyMessage(0);
                break;
            case MotionEvent.ACTION_UP:
                mHandler.removeCallbacksAndMessages(null);
                break;
        }
        return false;
    }

    public interface BackspaceEventListener {
        void onReceivedBackspaceEvent();
    }
}
